package dao

import (
	"go_my_framework/app/core/db"
	"go_my_framework/app/model"
	"time"
)

type PurviewDao interface {
	FindRow(id int) (model.Purview, error)
	FindRowByUrl(url string) (model.Purview, error)
	GetList(page int, limit int, name string) ([]model.Purview, int64, error)
	Create(name string, pid int, url string, isShow int8, sort int, icon string) error
	Update(id int, name string, pid int, url string, isShow int8, sort int, icon string) error
	Del(id int) error
	GetListByIds(ids []int, field []string) (data []model.Purview, err error)
}

func NewPurviewDaoImpl() PurviewDao {
	return new(PurviewDaoImpl)
}

type PurviewDaoImpl struct {

}

func (p *PurviewDaoImpl) FindRow(id int) (data model.Purview, err error) {
	err = db.Instance().
		Model(model.Purview{}).
		Where("id = ?", id).
		First(&data).
		Error
	return data, err
}

func (p *PurviewDaoImpl) FindRowByUrl(url string) (data model.Purview, err error) {
	err = db.Instance().
		Model(model.Purview{}).
		Where("url = ?", url).
		First(&data).
		Error
	return data, err
}

func (p *PurviewDaoImpl) GetList(page int, limit int, name string) (data []model.Purview, count int64, err error) {
	obj := db.Instance().Model(model.Purview{})
	if name != "" {
		obj = obj.Where("name = ?", name)
	}
	obj = obj.Count(&count)
	err = obj.Limit(limit).Offset((page - 1) * limit).Find(&data).Error
	return
}

func (p *PurviewDaoImpl) GetListByIds(ids []int, field []string) (data []model.Purview, err error) {
	db.Instance().
		Model(model.Purview{}).
		Where("id in ?", ids).
		Select(field).
		Find(&data)
	return data, nil
}

func (p *PurviewDaoImpl) Create(name string, pid int, url string, isShow int8, sort int, icon string) error {
	dateTime := time.Now().Format("2006-01-02 15:04:05")
	data := model.Purview{
		Name:      name,
		Pid:       pid,
		Url:       url,
		IsShow:    isShow,
		Sort:      sort,
		Icon:      icon,
		CreatedAt:  dateTime,
		UpdatedAt:  dateTime,
	}
	return db.Instance().Model(model.Purview{}).Create(&data).Error
}

func (p *PurviewDaoImpl) Update(id int, name string, pid int, url string, isShow int8, sort int, icon string) error {
	data := make(map[string]interface{})
	data["name"] = name
	data["pid"] = pid
	data["url"] = url
	data["is_show"] = isShow
	data["sort"] = sort
	data["icon"] = icon
	return db.Instance().Model(model.Purview{}).Where("id = ?", id).Updates(data).Error
}

func (p *PurviewDaoImpl) Del(id int) error {
	return db.Instance().Where("id = ?", id).Delete(model.Purview{}).Error
}